<?php
/**
 * Celebrio Core
 * 
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    Celebrio
 * @subpackage Core
 */
namespace Celebrio\Core;

use Nette\Object;
use Nette\Environment;

use Celebrio\Core\CriticalException;

use Celebrio\AccessControl\AclConstants;

use dibi;

/**
 * Critical features
 *
 * @author pavel
 */
abstract class CriticalFeatures extends Object {
    
    /**
     * Check whether there is any problem which may cause Critical mode.
     * 
     * @throws CriticalException where any problem occurs
     */
    public static function check() {
        self::checkDatabaseConnection();
        self::checkBasicAcl();
    }
    
    private static function checkDatabaseConnection() {
        if (!dibi::isConnected()) {
            throw new CriticalException("Database connection has not been set up yet.");
        }
    }
    
    /**
     * For now, just checks whether table ACL exists and if there are ANY records in ACL table.
     */
    private static function checkBasicAcl() {
        // TODO this does not work because mssql2005 driver does not support reflection
//        $existing_tables = dibi::getDatabaseInfo()->getTableNames();
//        if (!in_array("acl", $existing_tables)) {
//            throw new CriticalException("Table ACL does not exists. ACL module has probably not been installed yet.");
//        }

        // TODO temporary solution - we handle every dibi exception as incorrect state
        try {
            $count = dibi::select("id")->from("acl")->count();
            if ($count == 0) {
                throw new CriticalException("There are no ACL records in DB.");
            }
        } catch (\DibiException $e) {
            throw new CriticalException("Dibi error - it probably means ACL table does not exist.", null, $e);
        }
    }
    
}

